package app.productmanagement.web.ProductTag.service;

import app.productmanagement.web.ProductAndTag.Service.impl.ProductTagServiceInterface;
import app.productmanagement.web.ProductTag.CopyTag.CopyTag;
import app.productmanagement.web.ProductTag.Pojo.Tag;
import app.productmanagement.Pojo.Result;
import app.productmanagement.web.ProductTag.Pojo.TagRequest;
import app.productmanagement.web.ProductTag.Pojo.tagLimitVo;
import app.productmanagement.web.ProductTag.mapper.TagMapper;
import app.productmanagement.web.ProductTag.service.impl.TagServiceInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TagService extends ServiceImpl<TagMapper, Tag> implements TagServiceInterface {
    // 注入 Tag Mapper
    private final TagMapper tagMapper;

    // 注入 copy 类
    private final CopyTag cp;
    // 添加标签
    public Result<Tag> addTag(TagRequest tagRequest) {

        // 需要检查标签是否存在
        List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<Tag>().eq(Tag::getName, tagRequest.getName()));

        if ( tagList != null && !tagList.isEmpty()) {
            return Result.failure("标签名称已存在");
        }

        Tag tag = cp.CopyTagRequestToTag(tagRequest);

        if (tagMapper.insert(tag) > 0) {
            return Result.success(tag);
        } else {
            return Result.failure("添加标签失败");
        }
    }

    // 删除标签
    public Result<Boolean> deleteTag(Integer id) {

        if (tagMapper.deleteById(id) > 0) {
            return Result.success(true);
        } else {
            return Result.failure("删除标签失败，标签可能不存在");
        }
    }

    @Override
    public Boolean isTagExist(Integer tagId) {
        Tag tag = tagMapper.selectById(tagId);
        return tag != null;
    }

    // 查询全部标签
    // 需要分页查询
    public Result<tagLimitVo> getAllTags(int page, int limit) {
        Page<Tag> page1 = new Page<>(page, limit);
        Page<Tag> productPage = tagMapper.selectPage(page1, null);

        return Result.success(new tagLimitVo(productPage.getRecords(), productPage.getTotal(), productPage.getSize(), productPage.getCurrent()));
    }

    // 修改标签信息
    public Result<Tag> updateTag(int id, TagRequest tagRequest) {

        // 需要检查标签的名称是否存在
        if (!tagMapper.selectList(new LambdaQueryWrapper<Tag>().eq(Tag::getName, tagRequest.getName())).isEmpty()) {
            return Result.failure("标签名称已存在");
        }
        Tag tag = cp.CopyTagRequestToTag(tagRequest);
        tag.setId(id);
        if (tagMapper.updateById(tag) > 0) {
            return Result.success(tag);
        } else {
            return Result.failure("修改标签失败，标签可能不存在");
        }
    }
}
